//
//  LoginViewController.swift
//  SinaWb
//
//  Created by Jiang on 16/5/11.
//  Copyright © 2016年 Jiang. All rights reserved.
//

import UIKit
import SVProgressHUD



class LoginViewController: UIViewController {
    let webview : UIWebView  = UIWebView()
    override func loadView() {
        webview.delegate = self
        view  = webview
        
    }
    func CloseViewController(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
        SVProgressHUD.dismiss()
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(CloseViewController))
        let urlstring = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + appkey + "&redirect_uri=" + uri
        let URL = NSURL(string: urlstring)
        let request = NSURLRequest(URL: URL!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval:5)
        webview.loadRequest(request)
        
        
    }
    
    deinit{
        JkLog("登录界面 died")
    }
}
extension LoginViewController:UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
         SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let a : (Bool,String?) =  NetWorkTools.sharNetWorkTools.requstJudge(request)
        
        if a.1 != nil {
                ViewModel.sharViewModel.onlineGetUserMode(a.1!, finished: { (usermode, error) in
                    guard error == nil else{
                        return
                    }
                    ViewModel.sharViewModel.UserInfo = UserModel.GetTheUserMode()
                    //发送通知
                    NSNotificationCenter.defaultCenter().postNotificationName("JkmAppDelegate", object: nil, userInfo:nil)
                })
            
        }
        return a.0
    }

    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {

        if error!.code == -1001 {
            
            SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.Custom)
            SVProgressHUD.setBackgroundColor(UIColor.lightGrayColor())
            SVProgressHUD.showErrorWithStatus("您的网络不给力")
            

        }
    }
}